package controllers;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.ResourceBundle;
import java.util.concurrent.atomic.AtomicLong;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import Dao.DBConnect;
import application.Main;
import com.sun.org.apache.xalan.internal.xsltc.compiler.Parser;
import javafx.application.Platform;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import models.CarProductModel;
import models.OrderModel;
import models.ShopModel;


public class CustomerController implements Initializable {

	static int userid;
	static String uname;
	static int shop_id;


	@FXML
	private Button btnEdit;
	@FXML
	private Label innerlb01;
	@FXML
	private Label innerlb02;
	@FXML
	private TextField innertxt;
	@FXML
	private VBox innervbox01;


	CarProductModel cpm;
	OrderModel od;

	/***** TABLEVIEW intel *********************************************************************/


	@FXML
	private HBox hb01;
	@FXML
	private Button btnDel;
	@FXML
	private HBox hb02;
	@FXML
	private TableView<CarProductModel> tblProduct2;
	@FXML
	private TableColumn<CarProductModel, String> product_name;
	@FXML
	private TableColumn<CarProductModel, Long> product_price;
	@FXML
	private TableColumn<CarProductModel, Integer> pid;

	@FXML
	private TableView<OrderModel> order_view01;
	@FXML
	private TableColumn<OrderModel, Integer> oid;
	@FXML
	private TableColumn<OrderModel, String> product_name_o;
	@FXML
	private TableColumn<OrderModel, String> order_status;
	@FXML
	private TableColumn<OrderModel, Integer> pur_num;


	@FXML
	private TableView<OrderModel> order_view02;
	@FXML
	private TableColumn<OrderModel, Integer> oid2;
	@FXML
	private TableColumn<OrderModel, String> product_name_o2;
	@FXML
	private TableColumn<OrderModel, String> order_status2;
	@FXML
	private TableColumn<OrderModel, Integer> pur_num2;

	@FXML
	private Label lbinfo;

	ButtonType foo = new ButtonType("OK", ButtonBar.ButtonData.OK_DONE);
	ButtonType bar = new ButtonType("Cancel", ButtonBar.ButtonData.CANCEL_CLOSE);
	Alert a = new Alert(Alert.AlertType.NONE,"",foo,bar);
	Alert b = new Alert(Alert.AlertType.CONFIRMATION,"",foo);




	public void initialize(URL location, ResourceBundle resources) {

		pid.setCellValueFactory(new PropertyValueFactory<CarProductModel, Integer>("proId"));
		product_name.setCellValueFactory(new PropertyValueFactory<CarProductModel, String>("proName"));
		product_price.setCellValueFactory(new PropertyValueFactory<CarProductModel, Long>("proPrice"));
		pid.setStyle( "-fx-alignment: CENTER;");
		product_name.setStyle( "-fx-alignment: CENTER;");
		product_price.setStyle( "-fx-alignment: CENTER;");
		tblProduct2.setVisible(Boolean.FALSE);
		// auto adjust width of columns depending on their content

		tblProduct2.setColumnResizePolicy((param) -> true);
		Platform.runLater(() -> customResize(tblProduct2));
		oid.setCellValueFactory(new PropertyValueFactory<OrderModel, Integer>("id"));
		product_name_o.setCellValueFactory(new PropertyValueFactory<OrderModel, String>("product_name"));
		order_status.setCellValueFactory(new PropertyValueFactory<OrderModel, String>("order_status"));
		pur_num.setCellValueFactory(new PropertyValueFactory<OrderModel, Integer>("p_num"));
		order_view01.setVisible(Boolean.FALSE);
		oid.setStyle( "-fx-alignment: CENTER;");
		product_name_o.setStyle( "-fx-alignment: CENTER;");
		order_status.setStyle( "-fx-alignment: CENTER;");
		pur_num.setStyle( "-fx-alignment: CENTER;");
//		hb01.setVisible(Boolean.FALSE);
//		hb02.setVisible(Boolean.FALSE);
		innervbox01.setVisible(Boolean.FALSE);

		oid2.setCellValueFactory(new PropertyValueFactory<OrderModel, Integer>("id"));
		product_name_o2.setCellValueFactory(new PropertyValueFactory<OrderModel, String>("product_name"));
		order_status2.setCellValueFactory(new PropertyValueFactory<OrderModel, String>("order_status"));
		pur_num2.setCellValueFactory(new PropertyValueFactory<OrderModel, Integer>("p_num"));
		order_view02.setVisible(Boolean.FALSE);
		oid2.setStyle( "-fx-alignment: CENTER;");
		product_name_o2.setStyle( "-fx-alignment: CENTER;");
		order_status2.setStyle( "-fx-alignment: CENTER;");
		pur_num2.setStyle( "-fx-alignment: CENTER;");


//  init cb list




	}

	public void customResize(TableView<?> view) {

		AtomicLong width = new AtomicLong();
		view.getColumns().forEach(col -> {
			width.addAndGet((long) col.getWidth());
		});
		double tableWidth = view.getWidth();

		if (tableWidth > width.get()) {
			view.getColumns().forEach(col -> {
				col.setPrefWidth(col.getWidth()+((tableWidth-width.get())/view.getColumns().size()));
			});
		}
	}

	public void viewProduct() throws IOException {
		System.out.println("current sid is " + shop_id);
		order_view01.setVisible(Boolean.FALSE);
		order_view02.setVisible(Boolean.FALSE);
//		hb01.setVisible(Boolean.FALSE);
//		hb02.setVisible(Boolean.FALSE);
		innervbox01.setVisible(Boolean.FALSE);
		tblProduct2.setVisible(Boolean.TRUE);
		tblProduct2.getItems().setAll(cpm.getAllProductwithShop(shop_id));
		lbinfo.setText("Welcome " + uname + " now you are viewing the product");


	}

	/***** End TABLEVIEW intel *********************************************************************/

	public void logout() {
		// System.exit(0);
		try {
			AnchorPane root = (AnchorPane) FXMLLoader.load(getClass().getResource("/views/LoginView.fxml"));
			Scene scene = new Scene(root);
			scene.getStylesheets().add(getClass().getResource("/application/styles.css").toExternalForm());
			Main.stage.setScene(scene);
			Main.stage.setTitle("Login");

		} catch (Exception e) {
			System.out.println("Error occured while inflating view: " + e);
		}
	}



	public static void setUserid(int user_id) {
		userid = user_id;
		System.out.println("Welcome id " + userid);
	}
	public static void setUname(String user_name) {
		uname = user_name;
		System.out.println("Welcome id " + uname);

	}

	public static void setSid(int sid) {
		shop_id = sid;
		System.out.println("Welcome Shop " + shop_id);

	}


	public CustomerController() {


		cpm = new CarProductModel();
		od = new OrderModel();

	}

	public void purchaseOrder(MouseEvent mouseEvent) {

		System.out.println("mouse click");
		TablePosition tablePosition=tblProduct2.getSelectionModel().getSelectedCells().get(0);
		int row=tablePosition.getRow();
		CarProductModel item=tblProduct2.getItems().get(row);
		TableColumn tableColumn=tablePosition.getTableColumn();
//		String data= (String) tableColumn.getCellObservableValue(item).getValue();
//		System.out.println(data);
//		System.out.println(userid);
		CarProductModel cpms1 = tblProduct2.getSelectionModel().getSelectedItem();
		System.out.println(cpms1.toString());

		TextInputDialog dialog = new TextInputDialog("Enter quantity to create order");
		dialog.setTitle("U&E Car Dealer Shop Portal");
		dialog.setHeaderText("Create Transaction");
		dialog.setContentText("Please enter the purchase quantity:");
		Optional<String> result = dialog.showAndWait();
		if (result.isPresent()) {
			if (isValid(result.get())){
				System.out.println("Enter entry is : " + result.get());
	//            cm.insertRecord(userid,Double.parseDouble(result.get()));
				od.insertRecord(userid, Integer.parseInt(result.get()),cpms1.getProId());
	//			cpm.insertRecord(userid, Integer.parseInt(result.get()),cpms1.getProId());
				System.out.println(cpms1.toString() );
				b.setContentText("Order Created !!!");
				b.setHeaderText("");
				b.showAndWait();}
			else {
				b.setContentText("Must input number!!!");
				b.setHeaderText("");
				b.showAndWait();
			}
		}

	}

	public void viewOrders(ActionEvent actionEvent) {
		tblProduct2.setVisible(Boolean.FALSE);
		order_view01.setVisible(Boolean.TRUE);
		order_view02.setVisible(Boolean.FALSE);
		btnEdit.setDisable(true);
		btnDel.setDisable(true);
//		hb01.setVisible(Boolean.TRUE);
//		hb02.setVisible(Boolean.TRUE);
		innervbox01.setVisible(Boolean.TRUE);
		order_view01.getItems().setAll(od.getAll(userid));
		lbinfo.setText("Welcome " + uname + " now you are viewing all your orders");
	}



	public void deleteorder(MouseEvent mouseEvent) {

		a.setAlertType(Alert.AlertType.CONFIRMATION);
		a.setContentText("Do you want to delete the record??");
		a.setHeaderText("");

		Optional<ButtonType> result = a.showAndWait();

		if (result.get() == foo) {
			ObservableList<OrderModel> selectedRows, allOrder;
			allOrder = order_view01.getItems();

			//this gives us the rows that were selected
			selectedRows = order_view01.getSelectionModel().getSelectedItems();

			//loop over the selected rows and remove the Person objects from the table
			for (OrderModel order: selectedRows)
			{
				allOrder.remove(order);
				System.out.println(order.getId());
				od.deleteRecord(order.getId());
			}
			btnEdit.setDisable(true);
			btnDel.setDisable(true);
			b.setContentText("Order Deleted !!!");
			b.setHeaderText("");
			b.showAndWait();
		}

	}

	public static boolean isValid(String s)
	{

		Pattern p = Pattern.compile("[0-9]+");

		Matcher m = p.matcher(s);
		return (m.find() && m.group().equals(s));
	}

	public void orderUpdate(MouseEvent mouseEvent) {

		a.setAlertType(Alert.AlertType.CONFIRMATION);
		a.setContentText("Do you want to update the record??");
		a.setHeaderText("");

		Optional<ButtonType> result = a.showAndWait();

		if (result.get() == foo) {
			ObservableList<OrderModel> selectedRows, allOrder;
			allOrder = order_view01.getItems();

			//this gives us the rows that were selected
			selectedRows = order_view01.getSelectionModel().getSelectedItems();

			//loop over the selected rows and remove the Person objects from the table
			for (OrderModel order: selectedRows)
			{
//				allOrder.remove(order);
				System.out.println(order.getId());
				if (isValid(innertxt.getText())) {
					od.editRecord(order.getId(), Integer.parseInt(innertxt.getText()));
					b.setContentText("Order Updated!!!");
					b.setHeaderText("");
					b.showAndWait();
				}
				else {
					System.out.println("Please input a valid number");
					Alert al = new Alert(Alert.AlertType.WARNING);
					al.setContentText("Please input a valid number");
					al.setHeaderText("");
					al.showAndWait();
				}

				order_view01.getItems().setAll(od.getAll(userid));

			}

			btnEdit.setDisable(true);
			btnDel.setDisable(true);

		}

	}






	public void editOrder(MouseEvent mouseEvent) {
		ObservableList<OrderModel> selectedRows, allOrder;
		allOrder = order_view01.getItems();

		//this gives us the rows that were selected
		selectedRows = order_view01.getSelectionModel().getSelectedItems();

		//loop over the selected rows and remove the Person objects from the table
		for (OrderModel order: selectedRows)
		{
			innerlb01.setText(order.getProduct_name());
			innerlb02.setText(order.getOrder_status());
			innertxt.setText(String.valueOf(order.getP_num()));
		}
		btnEdit.setDisable(false);
		btnDel.setDisable(false);
	}

	public void viewHisOrders(ActionEvent actionEvent) {

		tblProduct2.setVisible(Boolean.FALSE);
		order_view01.setVisible(Boolean.FALSE);
		order_view02.setVisible(Boolean.TRUE);

		order_view02.getItems().setAll(od.getHis(userid));
		lbinfo.setText("Welcome " + uname + " now you are viewing all your orders");
	}
}
